package com.sitanyun.merchant.guide.frament.view.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.sitanyun.merchant.guide.R;
import com.sitanyun.merchant.guide.base.BaseActivity;
import com.sitanyun.merchant.guide.base.ToastUtil;
import com.sitanyun.merchant.guide.bean.ImageLoadBean;
import com.sitanyun.merchant.guide.callback.StringCallbacks;
import com.sitanyun.merchant.guide.url.Urls;
import com.sitanyun.merchant.guide.weiht.GlideEngine;
import com.sitanyun.merchant.guide.weiht.ImageLoadUtrils;
import com.sitanyun.merchant.guide.weiht.PictureUtils;
import com.sitanyun.merchant.guide.weiht.SharedPreferenceReal;
import com.sitanyun.merchant.guide.weiht.SharedPreferenceUtil;
import com.zhy.http.okhttp.OkHttpUtils;

import java.io.IOException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.MediaType;

/**
 * 身份证验证
 */
public class RealIDActivity extends BaseActivity {


    @BindView(R.id.cn_zm)
    ImageView cnZm;
    @BindView(R.id.cn_gh)
    ImageView cnGh;
    public static final int RC_CHOOSE_PHOTO = 2;
    @BindView(R.id.tv_zm)
    TextView tvZm;
    @BindView(R.id.tv_fm)
    TextView tvFm;
    @BindView(R.id.tv_return)
    ImageView tvReturn;
    @BindView(R.id.tv_title_str)
    TextView tvTitleStr;
    @BindView(R.id.ids_name)
    TextView idsName;
    @BindView(R.id.tv_right_key)
    TextView tvRightKey;
    @BindView(R.id.sms_login)
    TextView smsLogin;
    private String TAKE_PHOTO_PATH = Environment.getExternalStorageDirectory().getAbsolutePath();
    private ImageLoadBean.DataBean imagelist;
    private String filePath;
    private ImageLoadBean.DataBean imagelist2;
    private String filePath2;
    private String fileId = "";
    private String fileIds = "";
    private String namesx;

    @Override
    public int getLayoutId() {
        return R.layout.activity_real_id;
    }

    @Override
    public void initData(Bundle savedInstanceState) {

        tvTitleStr.setText("身份证上传");
           //获取接收数据
        String names = getIntent().getStringExtra("names");
        String str = names.substring(getIntent().getStringExtra("names").length() - 1);
       //进行隐藏
        for (int i = 1; i < names.length(); i++) {
            if (i == 1) {
                namesx = names.replaceAll(names, "*");
            } else if (i == 2) {
                namesx = names.replaceAll(names, "**");
            } else {
                namesx = names.replaceAll(names, "***");
            }
        }
        String name = namesx + str;
        //   String names= StringReplaceUtil.userNameReplaceWithStar(getIntent().getStringExtra("names"));
        idsName.setText("请上传" + name + "本人身份证照片");
        if (getIntent().getStringExtra("isIndividuals").equals("1")) {
            if (!getIntent().getStringExtra("fileid").isEmpty()) {
                Glide.with(RealIDActivity.this).load(getIntent().getStringExtra("picid")).into(cnZm);
                fileId = getIntent().getStringExtra("fileid");
                tvZm.setVisibility(View.GONE);
            cnZm.setClickable(false);
            }
            if (!getIntent().getStringExtra("fileids").isEmpty()) {
                Glide.with(RealIDActivity.this).load(getIntent().getStringExtra("picbackid")).into(cnGh);
                fileIds = getIntent().getStringExtra("fileids");
                tvFm.setVisibility(View.GONE);
           cnGh.setClickable(false);
            }
        }else {
            if (!SharedPreferenceReal.getStringData("filepath").isEmpty()){
                Glide.with(RealIDActivity.this).load(SharedPreferenceReal.getStringData("filepath")).into(cnZm);
                  tvZm.setVisibility(View.GONE);
            }
            if (!SharedPreferenceReal.getStringData("filepath2").isEmpty()){
                Glide.with(RealIDActivity.this).load(SharedPreferenceReal.getStringData("filepath2")).into(cnGh);
                   tvFm.setVisibility(View.GONE);
            }

        }


    }
//返回
    @Override
    public void initView() {
        tvReturn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                finish();
            }
        });

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    /**
     * 点击事件
     * @param view
     */
    @OnClick({R.id.cn_zm, R.id.cn_gh})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            //上传身份证正面
            case R.id.cn_zm:
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    //未授权，申请授权(从相册选择图片需要读取存储卡的权限)
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, RC_CHOOSE_PHOTO);
                } else {
                    //已授权，获取照片
                    //  choosePhoto();
                    PictureSelector.create(RealIDActivity.this)
                            .openGallery(PictureMimeType.ofImage())
                            .selectionMode(PictureConfig.SINGLE)
                            .loadImageEngine(GlideEngine.createGlideEngine())
                            .forResult(PictureConfig.CHOOSE_REQUEST);
                }
                break;
                //反面
            case R.id.cn_gh:
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    //未授权，申请授权(从相册选择图片需要读取存储卡的权限)
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, RC_CHOOSE_PHOTO);
                } else {
                    //已授权，获取照片
                    //  choosePhoto();
                    PictureSelector.create(RealIDActivity.this)
                            .openGallery(PictureMimeType.ofImage())
                            .selectionMode(PictureConfig.SINGLE)
                            .loadImageEngine(GlideEngine.createGlideEngine())
                            .forResult(2);
                }
                break;
        }
    }

    /**
     * 图片回调以及上传
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 2:
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    Log.i("TAG", "onActivityResult: 图片地址 ： " + new Gson().toJson(selectList));
                    if (selectList != null && selectList.size() != 0) {
                        //图片压缩
                        PictureUtils pictureUtils = new PictureUtils();
                        Bitmap bitmap = pictureUtils.getimage(selectList.get(0).getRealPath());
                        //获取文件类型
                        int i = selectList.get(0).getRealPath().lastIndexOf(".");
                        String s = selectList.get(0).getRealPath().substring(i, selectList.get(0).getRealPath().length());
                        String mitls = Calendar.getInstance().getTimeInMillis() + s;
                        String path = TAKE_PHOTO_PATH + "/" + mitls;
                        String mitl = path.substring(path.length() - 17);

                        try {
                            pictureUtils.saveBitmap(bitmap, path, 1);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        String img = ImageLoadUtrils.imageToBase64(path);
                        HashMap<String, String> hashMap = new HashMap<String, String>();
                        hashMap.put("shard", "data:image/jpg;base64," + img);
                        hashMap.put("fileUsage", "IDF");
                        hashMap.put("name", mitl);//文件名
                        hashMap.put("suffix", s);//后缀
                        hashMap.put("fileSize", selectList.get(0).getSize() + "");//文件大小
                        hashMap.put("shardKey", selectList.get(0).getId() + "");//分片主键
                        OkHttpUtils.postString()
                                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                                .addHeader("Content-Type", "application/json")
                                .addHeader("Authorization", "Bearer " + SharedPreferenceUtil.getStringData("token"))
                                .url(Urls.loadimage)
                                .content(new Gson().toJson(hashMap))
                                .build().execute(new StringCallbacks() {
                            @Override
                            public void onError(Call call, Exception e, int id) {

                            }

                            @Override
                            public void onResponse(String response, int id) {
                                ImageLoadBean baseEntity = new Gson().fromJson(response, ImageLoadBean.class);
                                if (baseEntity.getCode() == 0) {
                                    imagelist2 = baseEntity.getData();
                                    filePath2 = baseEntity.getData().getFilePath();
                                    fileIds = baseEntity.getData().getFileId();
                                    tvFm.setVisibility(View.GONE);
                                    Glide.with(RealIDActivity.this).load(filePath2).into(cnGh);
                                } else {
                                    ToastUtil.showToast(RealIDActivity.this, "" + baseEntity.getMsg());
                                }
                            }
                        });


                    }

                    break;
                case PictureConfig.CHOOSE_REQUEST:
                    List<LocalMedia> selectList1 = PictureSelector.obtainMultipleResult(data);
                    Log.i("TAG", "onActivityResult: 图片地址 ： " + new Gson().toJson(selectList1));
                    if (selectList1 != null && selectList1.size() != 0) {
                        //图片压缩
                        PictureUtils pictureUtils = new PictureUtils();
                        Bitmap bitmap = pictureUtils.getimage(selectList1.get(0).getRealPath());
                        //获取文件类型
                        int i = selectList1.get(0).getRealPath().lastIndexOf(".");
                        String s = selectList1.get(0).getRealPath().substring(i, selectList1.get(0).getRealPath().length());
                        String mitls = Calendar.getInstance().getTimeInMillis() + s;
                        String path = TAKE_PHOTO_PATH + "/" + mitls;
                        String mitl = path.substring(path.length() - 17);

                        try {
                            pictureUtils.saveBitmap(bitmap, path, 1);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        String img = ImageLoadUtrils.imageToBase64(path);
                        HashMap<String, String> hashMap = new HashMap<String, String>();
                        hashMap.put("shard", "data:image/jpg;base64," + img);
                        hashMap.put("fileUsage", "LI");
                        hashMap.put("name", mitl);//文件名
                        hashMap.put("suffix", s);//后缀
                        hashMap.put("fileSize", selectList1.get(0).getSize() + "");//文件大小
                        hashMap.put("shardKey", selectList1.get(0).getId() + "");//分片主键
                        OkHttpUtils.postString()
                                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                                .addHeader("Content-Type", "application/json")
                                .addHeader("Authorization", "Bearer " + SharedPreferenceUtil.getStringData("token"))
                                .url(Urls.loadimage)
                                .content(new Gson().toJson(hashMap))
                                .build().execute(new StringCallbacks() {
                            @Override
                            public void onError(Call call, Exception e, int id) {

                            }

                            @Override
                            public void onResponse(String response, int id) {
                                ImageLoadBean baseEntity = new Gson().fromJson(response, ImageLoadBean.class);
                                if (baseEntity.getCode() == 0) {
                                    tvZm.setVisibility(View.GONE);
                                    imagelist = baseEntity.getData();
                                    filePath = baseEntity.getData().getFilePath();
                                    fileId = baseEntity.getData().getFileId();
                                    Glide.with(RealIDActivity.this).load(filePath).into(cnZm);
                                } else {
                                    ToastUtil.showToast(RealIDActivity.this, "" + baseEntity.getMsg());
                                }
                            }
                        });


                    }
                    break;

            }
        }
    }

   //完成回调上一个界面
    @OnClick(R.id.sms_login)
    public void onViewClicked() {
        if (fileId.isEmpty()) {
            ToastUtil.showToast(RealIDActivity.this, "请上传身份证正面");
            return;
        }
        if (fileIds.isEmpty()) {
            ToastUtil.showToast(RealIDActivity.this, "请上传身份证反面");
            return;
        }
        Intent intent = new Intent();
        intent.putExtra("fileid", fileId);// 放入返回值  id
        intent.putExtra("fileids", fileIds);// 放入返回值
        intent.putExtra("filepath", filePath);// 放入返回值  路径
        intent.putExtra("filepath2", filePath2);// 放入返回值
        setResult(0, intent);// 放入回传的值,并添加一个Cod
        finish();
    }
}
